package dao

import (
	"common"
	"context"
	"encoding/json"
	"epai/internal/model"
	"gorm.io/gorm"
	"strings"
	"time"
)

type GetGoodsListResult struct {
	GoodsId     string `json:"goods_id"`
	Name        string `json:"name"`
	Cover       string `json:"cover"`
	IsHaveVideo bool   `gorm:"-" json:"is_have_video"`

	Tags   string   `json:"tags,omitempty"`
	TagArr []string `gorm:"-" json:"tag_arr"`

	Videos string `json:"videos,omitempty"`

	GoodsCategoryId   string `json:"goods_category_id"`
	GoodsCategoryName string `json:"goods_category_name"`

	ShopId        string  `json:"shop_id"`
	ShopName      string  `json:"shop_name"`
	ShopAddress   string  `json:"shop_address"`
	ShopLongitude float64 `json:"shop_longitude"`
	ShopLatitude  float64 `json:"shop_latitude"`

	ShopMobilePhone       string `json:"shop_mobile_phone"`
	ShopEstablishmentDate uint64 `json:"shop_establishment_date"`

	ShopExtPaoziId     string `json:"shop_ext_paozi_id"`
	Sex                string `json:"sex"`
	ChestCircumference string `json:"chest_circumference"`
	WaistCircumference int    `json:"waist_circumference"`
	HipCircumference   int    `json:"hip_circumference"`
	ShoeSize           int    `json:"shoe_size"`
	XiaoHongShuFans    int    `json:"xiao_hong_shu_fans"`
	DouYinFans         int    `json:"dou_yin_fans"`
	KuaiShouFans       int    `json:"kuai_shou_fans"`
	BZhanFans          int    `json:"bzhan_fans"`
	WeiBoFans          int    `json:"wei_bo_fans"`

	Height float64 `json:"height"`
	Weight float64 `json:"weight"`
}

type GetGoodsResult struct {
	GoodsId string `json:"goods_id"`
	Name    string `json:"name"`
	Cover   string `json:"cover"`

	Tags     string   `json:"tags,omitempty"`
	TagArr   []string `gorm:"-" json:"tag_arr"`
	Imgs     string   `json:"imgs,omitempty"`
	ImgArr   []string `gorm:"-" json:"img_arr"`
	Videos   string   `json:"videos,omitempty"`
	VideoArr []string `gorm:"-" json:"video_arr"`

	GoodsCategoryId   string `json:"goods_category_id"`
	GoodsCategoryName string `json:"goods_category_name"`

	ShopId        string  `json:"shop_id"`
	ShopName      string  `json:"shop_name"`
	ShopAddress   string  `json:"shop_address"`
	ShopLongitude float64 `json:"shop_longitude"`
	ShopLatitude  float64 `json:"shop_latitude"`

	ShopMobilePhone       string `json:"shop_mobile_phone"`
	ShopEstablishmentDate uint64 `json:"shop_establishment_date"`

	ShopExtPaoziId     string  `json:"shop_ext_paozi_id"`
	Sex                string  `json:"sex"`
	ChestCircumference string  `json:"chest_circumference"`
	WaistCircumference int     `json:"waist_circumference"`
	HipCircumference   int     `json:"hip_circumference"`
	ShoeSize           int     `json:"shoe_size"`
	XiaoHongShuFans    int     `json:"xiao_hong_shu_fans"`
	DouYinFans         int     `json:"dou_yin_fans"`
	KuaiShouFans       int     `json:"kuai_shou_fans"`
	BZhanFans          int     `json:"bzhan_fans"`
	WeiBoFans          int     `json:"wei_bo_fans"`
	Height             float64 `json:"height"`
	Weight             float64 `json:"weight"`
}

// AddGoods 将表格数据解析到商品数据表
func AddGoods(ctx context.Context, db *gorm.DB, data map[string][]string) error {
	// 先拿到所有的分类
	allGoodsCategory, err := GetAllGoodsCategory(ctx, db)
	if err != nil {
		return err
	}

	ma := make(map[string]string)
	for _, v := range allGoodsCategory {
		ma[v.Name] = v.GoodsCategoryId
	}

	// 推荐分类
	_, ok := ma["推荐"]
	if !ok {
		categoryOb, _ := AddGoodsCategory(ctx, db, "推荐")
		ma["推荐"] = categoryOb.GoodsCategoryId
	}
	// 先拿到所有的标签
	allTags, err := GetAllTag(ctx, db)
	if err != nil {
		return err
	}
	ma2 := make(map[string]string)
	for _, v := range allTags {
		ma2[v.Name] = v.TagId
	}

	// 统计有多少个商品
	count := len(data["goodsID"])

	// 对每个商品单独处理
	for i := 0; i < count; i++ {
		// 先判断分类存不存在，不存在就创建
		goodsCategoryId, ok := ma[data["类型"][i]]
		if !ok {
			categoryOb, _ := AddGoodsCategory(ctx, db, data["类型"][i])
			ma[data["类型"][i]] = categoryOb.GoodsCategoryId
			goodsCategoryId = categoryOb.GoodsCategoryId
		}
		isPushFlow := 2
		if data["为其推流"][i] == "推" {
			isPushFlow = 1
		}

		// 处理标签,判断标签存不存在，不存在就存入标签表
		tagsArr := strings.Split(data["标签"][i], " ")
		//videoArr := strings.Split(data["商品视频"][i], " ")
		for _, tag := range tagsArr {
			_, ok := ma[tag]
			if !ok {
				tagOb, _ := AddTag(ctx, db, tag)
				ma[tag] = tagOb.TagId
			}
		}
		tags, err := common.StrSplitToJson(data["标签"][i], " ")
		if err != nil {
			return err
		}
		imgs, err := common.StrSplitToJson(data["商品图"][i], " ")
		if err != nil {
			return err
		}
		videos, err := common.StrSplitToJson(data["商品视频"][i], " ")
		if err != nil {
			return err
		}
		publishDate, err := time.Parse("2006/1/2 15:04", data["上架时间"][i]) // 对上架时间转成时间戳，方便时间上的操作
		if err != nil {
			return err
		}

		// cover := imgsArr[0]// 默认为商品图的第一张
		cover := data["封面图"][i]
		cover = strings.TrimSpace(cover) // 去除行尾空格

		record := model.Goods{
			Name:            data["商品名称"][i],
			GoodsId:         data["goodsID"][i],
			GoodsCategoryId: goodsCategoryId,
			ShopId:          data["shopID"][i],
			IsPushFlow:      int8(isPushFlow),
			Tags:            tags,
			Imgs:            imgs,
			Videos:          videos,
			Cover:           cover,
			PublishDate:     uint64(publishDate.Unix()),
		}

		// 更新记录，如果记录不存在则创建新记录
		err = db.Where(model.Goods{GoodsId: record.GoodsId}).Assign(record).FirstOrCreate(&record).Error
		if err != nil {
			return err
		}
	}
	return nil
}

// DelGoods 删除单个商品
func DelGoods(ctx context.Context, db *gorm.DB, goodsId string) error {
	goods := &model.Goods{}
	err := db.WithContext(ctx).Where("goods_id = ?", goodsId).Delete(goods).Error
	return err
}

// DelGoodsSlice 批量删除商品（同时为了完整性，把goods_category对应的数据也一起删了）
func DelGoodsSlice(ctx context.Context, db *gorm.DB, GoodsId []string) error {
	// 直接开删
	err := db.WithContext(ctx).Where("goods_id IN ?", GoodsId).Delete(&model.Goods{}).Error // 错误忽略，后面还要处理
	//err := db.WithContext(ctx).Where("shop_id IN ?", ShopId).Delete(&model.ShopExtPaozi{}).Error
	if err != nil {
		return err
	}
	return err
}

// GetGoods 获取单个商品信息
func GetGoods(ctx context.Context, db *gorm.DB, goodsId string) (GetGoodsResult, error) {
	var result GetGoodsResult

	err := db.WithContext(ctx).
		Model(&model.Goods{}).Select("epai_goods.*,epai_shop_ext_paozi.*,epai_shop.name as shop_name,"+
		"epai_goods_category.name as goods_category_name,"+
		"epai_shop.address as shop_address,"+
		"epai_shop.establishment_date as shop_establishment_date,"+
		"epai_shop.mobile_phone as shop_mobile_phone,"+
		"epai_shop.shop_id as shop_id,"+
		"epai_shop.longitude as shop_longitude,"+
		"epai_shop.latitude as shop_latitude").
		Joins("left join epai_goods_category on epai_goods.goods_category_id = epai_goods_category.goods_category_id").
		Joins("left join epai_shop on epai_goods.shop_id = epai_shop.shop_id").
		Joins("left join epai_shop_ext_paozi on epai_goods.shop_id = epai_shop_ext_paozi.shop_id").
		Where("epai_goods.goods_id = ?", goodsId).
		Find(&result).Error
	if err != nil {
		return result, err
	}
	_ = json.Unmarshal([]byte(result.Tags), &result.TagArr)
	if len(result.TagArr) == 1 && len(result.TagArr[0]) == 0 {
		result.TagArr = []string{}
	}
	for index, item := range result.TagArr {
		result.TagArr[index] = strings.TrimSpace(item) // 去除行尾空格
	}
	result.Tags = ""
	_ = json.Unmarshal([]byte(result.Imgs), &result.ImgArr)
	if len(result.ImgArr) == 1 && len(result.ImgArr[0]) == 0 {
		result.ImgArr = []string{}
	}
	for index, item := range result.ImgArr {
		result.ImgArr[index] = strings.TrimSpace(item) // 去除行尾空格
	}
	result.Imgs = ""
	_ = json.Unmarshal([]byte(result.Videos), &result.VideoArr)
	if len(result.VideoArr) == 1 && len(result.VideoArr[0]) == 0 {
		result.VideoArr = []string{}
	}
	for index, item := range result.VideoArr {
		result.VideoArr[index] = strings.TrimSpace(item) // 去除行尾空格
	}
	result.Videos = ""
	return result, nil
}

// GetGoodsList 获取商品列表
func GetGoodsList(ctx context.Context, db *gorm.DB, categoryId string, page int, size int) ([]GetGoodsListResult, error) {
	var result []GetGoodsListResult

	err := db.WithContext(ctx).
		Model(&model.Goods{}).Select("epai_goods.*,epai_shop_ext_paozi.*,epai_shop.name as shop_name,"+
		"epai_goods_category.name as goods_category_name,"+
		"epai_shop.address as shop_address,"+
		"epai_shop.establishment_date as shop_establishment_date,"+
		"epai_shop.mobile_phone as shop_mobile_phone,"+
		"epai_shop.shop_id as shop_id,"+
		"epai_shop.longitude as shop_longitude,"+
		"epai_shop.latitude as shop_latitude").
		Joins("left join epai_goods_category on epai_goods.goods_category_id = epai_goods_category.goods_category_id").
		Joins("left join epai_shop on epai_goods.shop_id = epai_shop.shop_id").
		Joins("left join epai_shop_ext_paozi on epai_goods.shop_id = epai_shop_ext_paozi.shop_id").
		Where("epai_goods_category.goods_category_id = ?", categoryId).
		Limit(size).Offset((page - 1) * size).
		Find(&result).Error
	if err != nil {
		return result, err
	}
	for i := 0; i < len(result); i++ {
		_ = json.Unmarshal([]byte(result[i].Tags), &result[i].TagArr)
		if len(result[i].TagArr) == 1 && len(result[i].TagArr[0]) == 0 {
			result[i].TagArr = []string{}
		}
		result[i].IsHaveVideo = true
		if result[i].Videos == "[\"\"]" {
			result[i].IsHaveVideo = false
		}
		result[i].Videos = ""
		result[i].Tags = ""
	}
	return result, nil
}

// GetGoodsListRecommend 获取商品列表-推荐
func GetGoodsListRecommend(ctx context.Context, db *gorm.DB, page int, size int) ([]GetGoodsListResult, error) {
	var result []GetGoodsListResult

	err := db.WithContext(ctx).
		Model(&model.Goods{}).Select("epai_goods.*,epai_shop_ext_paozi.*,"+
		"epai_goods_category.name as goods_category_name,"+
		"epai_shop.name as shop_name,"+
		"epai_shop.address as shop_address,"+
		"epai_shop.establishment_date as shop_establishment_date,"+
		"epai_shop.mobile_phone as shop_mobile_phone,"+
		"epai_shop.shop_id as shop_id,"+
		"epai_shop.longitude as shop_longitude,"+
		"epai_shop.latitude as shop_latitude").
		Joins("left join epai_goods_category on epai_goods.goods_category_id = epai_goods_category.goods_category_id").
		Joins("left join epai_shop on epai_goods.shop_id = epai_shop.shop_id").
		Joins("left join epai_shop_ext_paozi on epai_goods.shop_id = epai_shop_ext_paozi.shop_id").
		Where("epai_goods.is_push_flow = ?", model.GoodsIsPushFlowOn).
		Limit(size).Offset((page - 1) * size).
		Find(&result).Error
	if err != nil {
		return result, err
	}
	for i := 0; i < len(result); i++ {
		_ = json.Unmarshal([]byte(result[i].Tags), &result[i].TagArr)
		if len(result[i].TagArr) == 1 && len(result[i].TagArr[0]) == 0 {
			result[i].TagArr = []string{}
		}
		result[i].IsHaveVideo = true
		if result[i].Videos == "[\"\"]" {
			result[i].IsHaveVideo = false
		}
		result[i].Videos = ""
		result[i].Tags = ""
	}
	return result, nil
}

// GetGoodsSum 获取商品数量
func GetGoodsSum(ctx context.Context, db *gorm.DB, categoryId string) (int64, error) {
	var count int64
	if len(categoryId) == 0 {
		err := db.WithContext(ctx).Model(&model.Goods{}).Count(&count).Error
		return count, err
	}
	err := db.WithContext(ctx).Model(&model.Goods{}).Where("goods_category_id = ?", categoryId).Count(&count).Error
	return count, err
}

// GetAllGoodsId 获取所有商品id
func GetAllGoodsId(ctx context.Context, db *gorm.DB) ([]string, error) {
	var result []string
	err := db.WithContext(ctx).Model(&model.Goods{}).Pluck("goods_id", &result).Error
	if err != nil {
		return nil, err
	}
	return result, err
}
